layui.use(['table', 'form', 'util', 'laydate'], function () {
    let table = layui.table,
        $ = layui.jquery,
        form = layui.form,
        laydate = layui.laydate;
    table.render({
        elem: '#table'
        , id: "dataTable"
        , url: '../task/pageList'
        , method: 'post'
        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        , cols: [
            [
                {type: 'checkbox', fixed: 'left'}
                , {field: 'taskName', title: '任务名称'}
                , {field: 'taskDescribe', width: 400, title: '任务详情'}
                , {field: 'progress', title: '任务进度'}
                , {
                field: 'state', width: 80, title: '任务状态'
                , templet: function (row) {
                    if (row.state === 0) {
                        return "待开始";
                    } else if (row.state === 1) {
                        return "进行中";
                    } else if (row.state === 2) {
                        return "测试中";
                    } else if (row.state === 3) {
                        return "暂停中";
                    } else {
                        return "结束";
                    }
                }
            }
                , {field: 'startTime', title: '预计开始时间'}
                , {field: 'actualTime', title: '实际开始时间'}
                , {field: 'endTime', title: '结束时间'}
                , {field: 'complete', title: '完成情况'}
            ]
        ]
        , page: true
        , response: {
            statusCode: 200 //重新指定成功的状态码为 200，table 组件默认为 0
        }
        , parseData: function (res) { //将原始数据解析成 table 组件所指定的数据
            if (res.status === 1) res.status = 200;
            return {
                code: res.status, //解析接口状态
                msg: res.msg, //解析提示文本
                count: res.count, //解析数据长度
                data: res.data //解析数据列表
            };
        }
    });

    function reload(param) {
        let where = $.extend({}, param || {});
        let page = {
            page: {
                curr: 1 //重新从第 1 页开始
            }, where: where
        };
        //执行重载
        table.reload('dataTable', page, 'data');
    }

    renderDate();

    function renderDate() {
        laydate.render({
            elem: 'input[name=startTime]' //或 elem: document.getElementById('test')、elem: lay('#test') 等
            , format: 'yyyy-MM-dd HH:mm:ss'
            , value: new Date()
        });
        laydate.render({
            elem: 'input[name=actualTime]'
            , format: 'yyyy-MM-dd HH:mm:ss'
            , value: new Date()
        })
    }

    function getData() {
        let checkStatus = table.checkStatus('dataTable');
        let datas = checkStatus.data;
        if (datas.length !== 1) {
            layer.alert("请选择一条数据");
            return;
        }
        return datas[0];
    }

    function updateState(param) {
        //获取数据
        $.ajax({
            url: '../task/updateState',
            type: 'post',
            dataType: 'json',
            data: param,
            success: function (result) {
                if (result.status !== 200) {
                    layer.close();
                    layer.alert(result.msg);
                    return;
                }
                reload();
            }
        });
    }

    let active = {
        reload: function () {
            let key = $("#demoReload").attr("name");
            let param = {};
            param[key] = $("#demoReload").val();
            reload(param);
        }
        , add: function () {
            $('#formDom')[0].reset();
            layer.open({
                type: 1
                , title: "添加用户"
                , area: '600px'
                , shade: 0.2
                , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                , btn: ['提交', '取消']
                , btnAlign: 'c'
                , moveType: 1 //拖拽模式，0或者1
                , content: $("#formDom") /** 注意：DOM一定要放在body之外的地方，否则你会崩溃！！！！！**/
                , success: function (layero) {
                    //获取新窗口对
                    //form.render();
                    /*laydate.render([{
                        elem: 'input[name=startTime]' //或 elem: document.getElementById('test')、elem: lay('#test') 等
                        , format: 'yyyy-MM-dd HH:mm:ss'
                        , value: new Date()
                    }, {
                        elem: 'input[name=actualTime]'
                        , format: 'yyyy-MM-dd HH:mm:ss'
                    }]);*/
                }
                , yes: function () {
                    form.verify();
                    let data = form.val('example');
                    $.ajax({
                        url: '../task/save',
                        type: 'post',
                        dataType: 'json',
                        data: data,
                        success: function (result) {
                            if (result.status !== 200) {
                                layer.alert(result.msg);
                                return;
                            }
                            layer.closeAll();
                            reload();
                            layer.alert("保存成功");

                        }
                    });
                }
            });
        },
        deit: function () {
            layer.open({
                type: 1
                , title: "修改用户"
                , area: '600px'
                , shade: 0.2
                , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                , btn: ['提交', '取消']
                , btnAlign: 'c'
                , moveType: 1 //拖拽模式，0或者1
                , content: $("#formDom")
                , success: function (layero, index) {
                    //获取新窗口对
                    form.render();
                    let data = getData();
                    if (!data) {
                        layer.close(index);
                        return;
                    }
                    //获取数据
                    $.ajax({
                        url: '../task/getById',
                        type: 'post',
                        dataType: 'json',
                        data: {id: data.id},
                        success: function (result) {
                            if (result.status !== 200) {
                                layer.close(index);
                                layer.alert(result.msg);
                                return;
                            }
                            form.val('example', result.data);
                        }
                    })
                }
                , yes: function () {
                    form.verify();
                    let data = form.val('example');
                    $.ajax({
                        url: '../task/save',
                        type: 'post',
                        dataType: 'json',
                        data: data,
                        success: function (result) {
                            if (result.status !== 200) {
                                layer.alert(result.msg);
                                return;
                            }
                            layer.closeAll();
                            reload();
                            layer.alert("保存成功");

                        }
                    });
                }
            });
        },
        del: function () {
            let data = getData();
            if (!data) {
                return;
            }
            //获取数据
            $.ajax({
                url: '../task/del',
                type: 'post',
                dataType: 'json',
                data: {id: data.id},
                success: function (result) {
                    if (result.status !== 200) {
                        layer.close();
                        layer.alert(result.msg);
                        return;
                    }
                    reload();
                }
            })
        }
        , start: function () {
            let data = getData();
            if (!data) {
                return;
            }
            let param = {
                id: data.id,
                state: 1
            };
            updateState(param);

        }
        , stop: function () {
            let data = getData();
            if (!data) {
                return;
            }
            let param = {
                id: data.id,
                state: 3
            };
            updateState(param);
        }
        , test: function () {
            let data = getData();
            if (!data) {
                return;
            }
            let param = {
                id: data.id,
                state: 2
            };
            updateState(param);
        }
        , over: function () {
            layer.open({
                type: 1
                , offset: 'auto'
                , id: 'layerDemoauto'
                , content: '<div style="padding: 20px 100px;">确定完成工作？</div>'
                , btn: ['确定', '取消']
                , btnAlign: 'c' //按钮居中
                , shade: 0.2 //不显示遮罩
                , yes: function () {
                    let data = getData();
                    if (!data) {
                        return;
                    }
                    let param = {
                        id: data.id,
                        state: 4
                    };
                    layer.closeAll();
                    updateState(param);
                },
            });


        }
    };

    //监听行单击事件（双击事件为：rowDouble）
    table.on('rowDouble(table)', function (obj) {
        var data = obj.data;

        /* layer.alert(JSON.stringify(data), {
             title: '当前行数据：'
         });*/
        layer.open({
            type: 1
            , title: "任务详情"
            , area: '600px'
            , shade: 0.2
            , id: 'LAY_layuiproinfo' //设定一个id，防止重复弹出
            , btn: '关闭'
            , btnAlign: 'c'
            , moveType: 1 //拖拽模式，0或者1
            , content: $("#formInfo") /** 注意：DOM一定要放在body之外的地方，否则你会崩溃！！！！！**/
            , success: function (layero) {
                //获取新窗口对
                $("#formInfo p").each(function (index, itme) {
                    let name = $(itme).attr('name');
                    if (name === 'state') {
                        let value = data[name];
                        switch (value) {
                            case 0:
                                data[name] = '待开始';
                                break;
                            case 1:
                                data[name] = '进行中';
                                break;
                            case 2:
                                data[name] = '测试中';
                                break;
                            case 3:
                                data[name] = '暂停中';
                                break;
                            default:
                                data[name] = '结束';
                                break;
                        }
                    }
                    $(itme).text(data[name] || '');
                });
            }
        });
        //标注选中样式
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });
    $('.layui-body .layui-btn,#chatDom .layui-btn').on('click', function () {
        var othis = $(this), method = othis.data('method');
        active[method] ? active[method].call(this, othis) : '';
    });


    /**
     * 聊天IM相关代码
     **/
    let socket = new WebSocket('ws://127.0.0.1:12788/app?id=' + userinfo.id);
    //let socket = new WebSocket('ws://120.55.73.152:12788/app');
    socket.onopen = function (res) {
        let toData = {
            id: userinfo.id,
            name: userinfo.name,
            content: 'heartbeat'
        };
        let datajson = JSON.stringify(toData);
        socket.send(datajson);
        setInterval(function () {
            socket.send(datajson);
        }, 5000);
    };
    socket.onmessage = function (event) {

        let result = JSON.parse(event.data);
        if (result.content === 'connect') {
            return;
        }
        let html = handleMessage(result);
        layui.cache.socketHtml += html;
        $('.layim-chat-main ul').append(html);
        let ele = document.getElementById('IM-content');
        ele.scrollTop = ele.scrollHeight;
    };
    socket.onclose = function () {
        socket.close();
    };

    function handleMessage(result, islog) {
        let html = '';
        if (result.name === userinfo.name) {
            html = '<li class="layim-chat-mine">' +
                '   <div class="layim-chat-user"><img src="../img/touxiang.jpg">' +
                '       <cite><i>' + result.time + '</i><span>' + result.name + '</span></cite>' +
                '   </div>' +
                '   <div class="layim-chat-text chat-content-message">' + result.content + '</div>' +
                '</li>';
        } else {
            html = '<li>' +
                '   <div class="layim-chat-user"><img src="../img/touxiang.jpg">' +
                '       <cite><span>' + result.name + '</span><i>' + result.time + '</i></cite>' +
                '   </div>' +
                '   <div class="layim-chat-text chat-content-message">' + result.content + '</div>' +
                '</li>';
        }

        return html;
    }

    var activeIM = {
        chatIMDemo: function () {
            if (!userinfo.name) {
                layer.alert("请先注册聊天昵称");
                return;
            }
            layer.open({
                type: 1 //此处以iframe举例
                , title: '&#8203;'
                , area: ['640px', '520px']
                , id: 'LAY_layuiDom'
                , shade: 0
                , maxmin: true
                , moveType: 1
                , resize: false
                , content: $("#layui-layim-chat")
                //, zIndex: layer.zIndex //重点1
                , success: function (layero) {
                    $(layero[0]).addClass('layui-box layui-layim-chat');
                    $(layero[0]).find('.layim-chat-username').text(userinfo.name);
                    if (layui.cache.socketHtml) {
                        $('#chatContent').html(layui.cache.socketHtml);
                    }
                    $('#LAY_layuiDom .layim-send-btn').on('click', function () {
                        var othis = $(this), method = othis.data('method');
                        activeIM[method] ? activeIM[method].call(this, othis) : '';
                    });
                }
            });
        },
        chatRegister: function () {
            layer.open({
                type: 1 //此处以iframe举例
                , title: '注册昵称'
                , id: 'LAY_layuiRegister'
                , btn: '注册'
                , content: '<div class="layui-row" style="margin:30px;width: 200px">'
                    + '<div class="col-sm-12">'
                    + '<span class="input-group-addon"> 昵 称：</span>'
                    + '<input id="chatNickName" type="text" class="layui-input" placeholder="请输入">'

                    + '</div></div>'
                , success: function (layero) {

                },
                yes: function () {
                    let chatNickName = $('#chatNickName').val();
                    if (!userinfo.name) {
                        userinfo = {
                            id: '',
                            name: chatNickName.trim()
                        };
                    }
                    $("#Lay_open_register").hide();
                    layer.closeAll();
                }
            });
        },
        sendContent: function () {
            let content = $('#LAY_layuiDom textarea').val();
            if (!content) {
                return;
            }
            $('#LAY_layuiDom textarea').val('');
            let toData = {
                id: userinfo.id,
                name: userinfo.name,
                content: content,
                targetId: '9',
                time: new Date().toLocaleString()
            };
            socket.send(JSON.stringify(toData));
        },
        loadRecord: function () {
            $.ajax({
                url: '/chatRecord/getRecord',
                type: 'post',
                dataType: 'json',
                data: {
                    userId1: userinfo.id,
                    userId2:'8',
                    dateTime:'2020-03-26'
                },
                success: function (result) {
                    if (result.status !== 200) {
                        return;
                    }
                    let html = '';
                    result.data.forEach(function (item, i) {
                        var data = JSON.parse(item.message);
                        html += handleMessage(data);
                    });
                    layui.cache.socketHtml = html;
                    $('.layim-chat-main ul').html(html);
                    let ele = document.getElementById('IM-content');
                    ele.scrollTop = ele.scrollHeight;
                }
            });
        }
    }
    $('.layui-body .layui-btn,#LAY_layuiDom .layim-send-btn').on('click', function () {
        var othis = $(this), method = othis.data('method');
        activeIM[method] ? activeIM[method].call(this, othis) : '';
    });

});

